/*
 * hc_sr04.c
 *
 *  Created on: 2017年7月31日
 *      Author: Case
 */

#include "hc_sr04.h"

void Start_Measure(void)
{
    int delay = 153;
    TRIG = 1; /* PA.4=1 output*/
    while(delay--);
    TRIG = 0; /* PA.4=0 output*/
}

/***********************************************************************************************************************
* Function Name: Get_Distance
* Description  : This function is used to get the distance.
* Arguments    : Count_value is the timer count value.
* Return Value : the actual distance.
***********************************************************************************************************************/
int Get_Distance(uint16_t Count_value)
{
    int length;

    /******************************************************************************************************************
        Attention:
        * 1250000 is current timer's clock frequency, it is changed by PCLKA in Clock Generator and Counter U counter
          source in MTU5. So if the clock frequency changed, we should change this number at the same time.
        * 340 is the speed of ultrasonic every second.
    *******************************************************************************************************************/
    length = (double)Count_value/1250*340/2;

    return length;
}


/***********************************************************************************************************************
* Function Name: Get_Average
* Description  : This function gets average distance in five times measure.
* Arguments    : None
* Return Value : average distance
***********************************************************************************************************************/
int Get_Average(int	higt[5])
{
    int i = 0;
    int distance = 0,average = 0;
    for(i = 0;i < 5;i++)
	{
		if(higt[i] < higt[i+1])		//最小值
		{
			distance = higt[i];
			higt[i] = higt[i+1];
			higt[i+1] = distance;
		}
	}
	for(i = 0;i < 4;i++)				//最大值
	{
		if(higt[i] > higt[i+1])
		{
			distance = higt[i];
			higt[i] = higt[i+1];
			higt[i+1] = distance;
		}
	}
	for(i = 0;i < 3;i++)
	{
		average += higt[i];
	}
    average = average/3;
    return average;
}
